<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-cn">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>java Class文件内部结构解析 - God Is Coder - 博客园</title>
<link type="text/css" rel="stylesheet" href="/bundles/blog-common.css?v=CFo7qU8PX574D_uabaLip0eHAfPkOQKz7wVlSUf2A9Q1"/>
<link id="MainCss" type="text/css" rel="stylesheet" href="/skins/SimpleBlue/bundle-SimpleBlue.css?v=g1Ly_5CnmgosFgcSP2WTmRocMrlS6IO9yhcnMXW9dOA1"/>
<link title="RSS" type="application/rss+xml" rel="alternate" href="http://www.cnblogs.com/aigongsi/rss"/>
<link title="RSD" type="application/rsd+xml" rel="EditURI" href="http://www.cnblogs.com/aigongsi/rsd.xml"/>
<link type="application/wlwmanifest+xml" rel="wlwmanifest" href="http://www.cnblogs.com/aigongsi/wlwmanifest.xml"/>
<script src="http://common.cnblogs.com/script/jquery.js" type="text/javascript"></script>  
<script type="text/javascript">var currentBlogApp = 'aigongsi', cb_enable_mathjax=false;</script>
<script src="/bundles/blog-common.js?v=dVqr0ue7y29mRAG2afMkFcSk38ChENfNlXrmAf_YHQE1" type="text/javascript"></script>
</head>
<body>
<a name="top"></a>

<div id="home">
<div id="header">
	<div id="blogTitle">
		
<!--done-->
<div class="title"><a id="Header1_HeaderTitle" class="headermaintitle" href="http://www.cnblogs.com/aigongsi/">God Is Coder</a></div>
<div class="subtitle">技术改变生活</div>



		
	</div><!--end: blogTitle 博客的标题和副标题 -->
	<div id="navigator">
		
<ul id="navList">
<li id="nav_sitehome"></li>
<li id="nav_myhome"><a id="MyLinks1_MyHomeLink" class="menu" href="http://www.cnblogs.com/aigongsi/">首页</a></li>
<li id="nav_q"><a class="menu" href="http://q.cnblogs.com/">博问</a></li>
<li id="nav_ing"><a class="menu" href="http://home.cnblogs.com/ing/">闪存</a></li>
<li id="nav_newpost"></li>
<li id="nav_contact"><a id="MyLinks1_ContactLink" class="menu" rel="nofollow" href="http://space.cnblogs.com/msg/send/God+Is+Coder">联系</a></li>
<li id="nav_rss"><a id="MyLinks1_Syndication" class="menu" href="http://www.cnblogs.com/aigongsi/rss">订阅</a>
<!--<a id="MyLinks1_XMLLink" class="aHeaderXML" href="http://www.cnblogs.com/aigongsi/rss"><img src="http://www.cnblogs.com/images/xml.gif" alt="订阅" /></a>--></li>
<li id="nav_admin"><a id="MyLinks1_Admin" class="menu" rel="nofollow" href="http://i.cnblogs.com/">管理</a></li>
</ul>

		<div class="blogStats">
			
			
			
		</div><!--end: blogStats -->
	</div><!--end: navigator 博客导航栏 -->
</div><!--end: header 头部 -->
<div id="main">
	<div id="mainContent">
	<div class="forFlow">
		

<!--done-->
<div id="topics">
	<div class = "post">
		<h1 class = "postTitle">
			<a id="cb_post_title_url" class="postTitle2" href="http://www.cnblogs.com/aigongsi/archive/2012/04/15/2450190.html">java Class文件内部结构解析</a>
		</h1>
		<div class="clear"></div>
		<div class="postBody">
			<div id="cnblogs_post_body"><p>大学的时候，就看过java虚拟机规范第二版，最近把最新的Java虚拟机规范第三版（java se 1.7版本）温习了一遍，发现java虚拟机规范中java class的文件结构部分并没有太大的变化，顺便也整理了一下。</p>
<p>java语言是跨平台的，所谓一次编写，到处运行。之所以是跨平台的，就是java定义了一套与操作系统，硬件无关的字节码格式，这个字节码就是用java class文件来表示的，java class文件内部定义了虚拟机可以识别的字节码格式，这个格式是平台无关性的，在linux系统或者在windows系统上都是一致的。这个就好比html文件，我们定义好规范，这个系统只要去按照规范显示出来里面的内容就好了。好比html就是class文件，浏览器就是虚拟机一样，通过浏览器去执行html的渲染过程，我们无论是用手机，Windows系统，苹果系统上网，显示出来的内容都是一样。 java虚拟机可以从class文件中加载预定义的字节码，也可以从网络，数据库，消息文件中加载字节码。</p>
<p>下面来说说java class的文件结构，java class文件结构是基于字节流的，用unicode进行编码。其实想想也可以完全用xml文件表示，只不过用xml表示的字节码文本体积可能会很大，占用空间，同时解析起来比较耗时，而且很容易被人为修改，导致未知错误。下面是class文件的内部结构</p>
<pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">ClassFile { 
u4 magic; 
u2 minor_version; 
u2 major_version; 
u2 constant_pool_count; 
cp_info constant_pool[constant_pool_count-1]; 
u2 access_flags; 
u2 this_class; 
u2 super_class; 
u2 interfaces_count; 
u2 interfaces[interfaces_count]; 
u2 fields_count; 
field_info fields[fields_count]; 
u2 methods_count; 
method_info methods[methods_count]; 
u2 attributes_count; 
attribute_info attributes[attributes_count]; 
}</pre>
<pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">&nbsp;</pre>
<pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">&nbsp;</pre>
<p>简要解释一下：</p>
<p>U4 代表由无符号四个字节组成</p>
<p>u4 magic ：是一个固定的数值，java虚拟机里面称为魔数 ，主要是用来标识是否为java虚拟机所支持的文件结构，目前是0xCAFEBABE</p>
<p>u2 minor_version; u2 major_version; 代表次版本号和主版本号</p>
<p>u2 constant_pool_count; cp_info constant_pool[constant_pool_count-1]; 这里面代表常量池个数以及常量池信息</p>
<p>u2 access_flags : 代表class访问标记，例如：public protected</p>
<p>u2 this_class : 代表这个类的名称 例如 java.lang.Object</p>
<p>u2 super_class : 代表父类名称</p>
<p>u2 interfaces_count; u2 interfaces[interfaces_count]; 实现的接口格式以及接口类名</p>
<p>u2 fields_count; field_info fields[fields_count]; 字段个数以及字段信息</p>
<p>u2 methods_count; method_info methods[methods_count]; 方法个数以及方法信息</p>
<p>u2 attributes_count; attribute_info attributes[attributes_count]; java class文件内部属性信息，和java语言定义的属性没有关系，纯粹就是给java虚拟机用的</p>
<p><a href="http://images.cnblogs.com/cnblogs_com/aigongsi/201204/201204151446376909.jpg"><img style="display: inline; border: 0px;" title="1" src="http://images.cnblogs.com/cnblogs_com/aigongsi/201204/201204151446378337.jpg" alt="1" width="563" height="577" border="0" data-pinit="registered" /></a></p>
<p>以上都是java虚拟机规范中定义的class文件内部结构信息，可以参考 <strong><em>Java</em></strong><strong><em>虚拟机规范 （Java SE 7版）</em></strong>这里就不细讲</p>
<pre>每种结构又都定义了自己的结构信息，例如：常量池结构，字段信息，方法信息，类信息，这几种结构之间又都互相引用，下面这幅图简要介绍了java class文件的内部结构信息</pre>
<p>其中常量池的里面的信息最为复杂，java虚拟机运行时刻的所有信息都是从常量池来获取的，常量池定义了一下几种结构</p>
<p><a href="http://images.cnblogs.com/cnblogs_com/aigongsi/201204/201204151441325478.jpg"><img style="display: inline; border-width: 0px;" title="2" src="http://images.cnblogs.com/cnblogs_com/aigongsi/201204/201204151441333003.jpg" alt="2" width="562" height="318" border="0" data-pinit="registered" /></a></p></div><div id="MySignature"></div>
<div class="clear"></div>
<div id="blog_post_info_block">
<div id="BlogPostCategory"></div>
<div id="EntryTag"></div>
<div id="blog_post_info">
</div>
<div class="clear"></div>
<div id="post_next_prev"></div>
</div>


		</div>
		<div class = "postDesc">posted @ <span id="post-date">2012-04-15 14:42</span> <a href='http://www.cnblogs.com/aigongsi/'>God Is Coder</a> 阅读(<span id="post_view_count">...</span>) 评论(<span id="post_comment_count">...</span>)  <a href ="http://i.cnblogs.com/EditPosts.aspx?postid=2450190" rel="nofollow">编辑</a> <a href="#" onclick="AddToWz(2450190);return false;">收藏</a></div>
	</div>
	<script type="text/javascript">var allowComments=true,isLogined=false,cb_blogId=112573,cb_entryId=2450190,cb_blogApp=currentBlogApp,cb_blogUserGuid='08b20b2c-fc73-e111-aa3f-842b2b196315',cb_entryCreatedDate='2012/4/15 14:42:00';loadViewCount(cb_entryId);</script>
	
</div><!--end: topics 文章、评论容器-->
<a name="!comments"></a><div id="blog-comments-placeholder"></div><script type="text/javascript">var commentManager = new blogCommentManager();commentManager.renderComments(0);</script>
<div id="comment_form" class="commentform">
<a name="commentform"></a>
<div id="divCommentShow"></div>
<div id="comment_nav"><span id="span_refresh_tips"></span><a href="javascript:void(0);" id="lnk_RefreshComments" onclick="return RefreshCommentList();">刷新评论</a><a href="#" onclick="return RefreshPage();">刷新页面</a><a href="#top">返回顶部</a></div>
<div id="comment_form_container"></div>
<div class="ad_text_commentbox" id="ad_text_under_commentbox"></div>
<div id="site_nav_under"><a href="http://www.cnblogs.com/" target="_blank" title="开发者的网上家园">博客园首页</a><a href="http://q.cnblogs.com/" target="_blank" title="程序员问答社区">博问</a><a href="http://news.cnblogs.com/" target="_blank" title="IT新闻">新闻</a><a href="http://home.cnblogs.com/ing/" target="_blank">闪存</a><a href="http://job.cnblogs.com/" target="_blank">程序员招聘</a><a href="http://kb.cnblogs.com/" target="_blank">知识库</a></div>
<div id="opt_under_post"></div>
<script type="text/javascript">
    var enableGoogleAd = canShowAdsense(); var googletag = googletag || {}; googletag.cmd = googletag.cmd || [];
    fixPostBodyFormat();
</script>
<div id="ad_under_post_holder">
<script type='text/javascript'>
    var googletag = googletag || {};
    googletag.cmd = googletag.cmd || [];
    (function () {
        if (enableGoogleAd) {
            var gads = document.createElement('script');
            gads.async = true;
            gads.type = 'text/javascript';
            var useSSL = 'https:' == document.location.protocol;
            gads.src = (useSSL ? 'https:' : 'http:') + '//www.googletagservices.com/tag/js/gpt.js';
            var node = document.getElementsByTagName('script')[0];
            node.parentNode.insertBefore(gads, node);
        }
    })();
</script>
<script type='text/javascript'>
    try {
        if (enableGoogleAd) {
            googletag.cmd.push(function () {
                googletag.defineSlot('/1090369/cnblogs_blogpost_C1_sitehome', [300, 250], 'div-gpt-ad-1346480159711-0').addService(googletag.pubads());
                googletag.defineSlot('/1090369/cnblogs_blogpost_C2', [468, 60], 'div-gpt-ad-1410860226396-0').addService(googletag.pubads());
                googletag.pubads().enableSingleRequest();
                googletag.enableServices();
            });
        };
    } catch (e) { }
</script>
<div id="google_ad_c1" class="c_ad_block">
    <div id='div-gpt-ad-1346480159711-0' style='width:300px; height:250px;'>
    <script type='text/javascript'>
        try {
            if (enableGoogleAd) {
                googletag.cmd.push(function () { googletag.display('div-gpt-ad-1346480159711-0'); });            
            } else {
                $('#div-gpt-ad-1346480159711-0').hide();
            }
    } catch (e) { }
    </script>
    </div>
</div>
</div>
<div id="under_post_news"></div>
<div id="google_ad_c2" class="c_ad_block">
<div id='div-gpt-ad-1410860226396-0' style='width:468px; height:60px;'>
<script type='text/javascript'>
try {
    if (enableGoogleAd) {
        googletag.cmd.push(function () { googletag.display('div-gpt-ad-1410860226396-0'); });
    } else {
        $('#div-gpt-ad-1346480159711-0').hide();
    }
} catch (e) { }
</script>
</div>
</div>
<div id="under_post_kb"></div>
<div id="HistoryToday" class="c_ad_block"></div>
<script type="text/javascript">
$(function () {
    loadNewsAndKb();
    loadBlogSignature();
    LoadPostInfoBlock(cb_blogId, cb_entryId, cb_blogApp, cb_blogUserGuid);
    GetPrevNextPost(cb_entryId, cb_blogId, cb_entryCreatedDate);
    loadOptUnderPost();
    GetHistoryToday(cb_blogId, cb_blogApp, cb_entryCreatedDate);
    setTimeout(function () { incrementViewCount(cb_entryId); }, 200);
});
</script>
</div>

	</div><!--end: forFlow -->
	</div><!--end: mainContent 主体内容容器-->

	<div id="sideBar">
		<div id="sideBarMain">
			
<!--done-->
<div class="newsItem">
<h3 class="catListTitle">公告</h3>
	<div id="blog-news"></div><script type="text/javascript">loadBlogNews();</script>
</div>

			<div id="calendar"><div id="blog-calendar" style="display:none"></div><script type="text/javascript">loadBlogDefaultCalendar();</script></div>
			
			<div id="leftcontentcontainer">
				<div id="blog-sidecolumn"></div><script type="text/javascript">loadBlogSideColumn();</script>
			</div>
			
		</div><!--end: sideBarMain -->
	</div><!--end: sideBar 侧边栏容器 -->
	<div class="clear"></div>
	</div><!--end: main -->
	<div class="clear"></div>
	<div id="footer">
		
<!--done-->
Copyright &copy;2015 God Is Coder
	</div><!--end: footer -->
</div><!--end: home 自定义的最大容器 -->
<!--PageEndHtml Block Begin-->
<script type="text/javascript">
var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://");
document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3Fcf070acf243cb7e2159e4b9dd542fdec' type='text/javascript'%3E%3C/script%3E"));
</script>
<!--PageEndHtml Block End-->
</body>
</html>
